package com.lou.springboot.service.impl;

import com.lou.springboot.common.PageResult;
import com.lou.springboot.dao.BlogCategoryDao;
import com.lou.springboot.entity.BlogCategory;
import com.lou.springboot.service.BlogCategoryService;
import com.lou.springboot.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BlogCategoryServiceImpl implements BlogCategoryService {

    @Autowired
    private BlogCategoryDao blogCategoryDao;

    public PageResult getBlogCategoryPage(PageUtil pageUtil) {
        List<BlogCategory> blogCategories = blogCategoryDao.findCategoryList(pageUtil);
        int total = blogCategoryDao.getTotalCategories();
        return new PageResult(blogCategories,total,pageUtil.getLimit(),pageUtil.getPage());
    }

    public Boolean saveBlogCategory(String categoryName,
                                    String categoryIcon) {
        BlogCategory temp = blogCategoryDao.selectByCategoryName(categoryName);
        if (temp == null) {
            BlogCategory blogCategory = new BlogCategory();
            blogCategory.setCategoryIcon(categoryIcon);
            blogCategory.setCategoryName(categoryName);
            return blogCategoryDao.insertBlogCategory(blogCategory) > 0;
        }
        return false;
    }

    @Transactional
    public Boolean deleteBatch(Integer[] ids) {
        if (ids.length < 1) {
            return false;
        }

        return blogCategoryDao.deleteBatch(ids) > 0;
    }

    public BlogCategory getBlogCategoryById(Integer categoryId) {
        return blogCategoryDao.selectByPrimaryKey(categoryId);
    }

    @Transactional
    public boolean updateCategory(Integer categoryId, String categoryName, String categoryIcon) {
        BlogCategory blogCategory = blogCategoryDao.selectByPrimaryKey(categoryId);
        if (blogCategory != null){
            blogCategory.setCategoryName(categoryName);
            blogCategory.setCategoryIcon(categoryIcon);
            return blogCategoryDao.updateCategory(blogCategory) > 0;
        }
        return false;
    }

    @Override
    public List<BlogCategory> getAllCategories() {
        return blogCategoryDao.findCategoryList(null);
    }
}
